package luongvd.appdownload;

import luongvd.appdownload.common.ServerConnectionUtils;
import luongvd.appdownload.common.Utils;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	Context mContext;
	static int timeReset = 40000;
	String userLogin;
	String appPackageName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		userLogin = "";
		setContentView(R.layout.activity_main);
		ServerDelegate.connectServer(handler, ServerDelegate.LINK_GET_URL);
	}

	

	@Override
	protected void onDestroy() {
		Intent intent = new Intent(mContext, InstallCheckerService.class);
		stopService(intent);
		android.os.Process.killProcess(android.os.Process.myPid());
		super.onDestroy();
	}

	public static void doRestart(Context c) {
		try {
			if (c != null) {
				PackageManager pm = c.getPackageManager();
				if (pm != null) {
					Intent mStartActivity = pm.getLaunchIntentForPackage(c
							.getPackageName());
					if (mStartActivity != null) {
						mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						int mPendingIntentId = 223344;
						PendingIntent mPendingIntent = PendingIntent
								.getActivity(c, mPendingIntentId,
										mStartActivity,
										PendingIntent.FLAG_CANCEL_CURRENT);
						AlarmManager mgr = (AlarmManager) c
								.getSystemService(Context.ALARM_SERVICE);
						mgr.set(AlarmManager.RTC,
								System.currentTimeMillis() + 100,
								mPendingIntent);
						// kill the application
						System.exit(0);
					} else {
					}
				} else {
				}
			} else {
			}
		} catch (Exception ex) {
		}
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == ServerConnectionUtils.CONNECT_TO_SERVER_MESSAGE_SUCCESSFUL) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					String keyAction = dataJSONObject.getString("action");
					String keyStatus = dataJSONObject.getString("status");
					if (keyAction.equals("getLink")) {
						if (Integer.parseInt(keyStatus) > 0) {
							JSONObject jsonData = new JSONObject();
							jsonData = dataJSONObject.getJSONObject("data");
							appPackageName = jsonData.getString("link");
//							appPackageName = "com.haian.slidealbum";
							try {
								startActivity(new Intent(Intent.ACTION_VIEW,
										Uri.parse(Utils.getGooglePlayStoreUrl(
												appPackageName, mContext))));
								ServerDelegate.connectServer(handler,
										ServerDelegate.LINK_SET_DONE);
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					} else if (keyAction.equals("checkHasLogin")) {
						if (Integer.parseInt(keyStatus) > 0) {
							Log.d("Luong",
									"==================================== Notify login status: "
											+ userLogin);
						}
					} else if (keyAction.equals("setDone")) {
						Toast.makeText(mContext, "View Successful",
								Toast.LENGTH_LONG).show();
						try {
							Thread.sleep(timeReset);

						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						userLogin = Utils.getAccountLoginGoogleFirst(mContext);
						Log.d("Luong",
								"========================== Check userLogin: "
										+ userLogin);
						if (userLogin.length() > 0) {
							ServerDelegate.connectServerToCheckLogin(handler,
									ServerDelegate.LINK_CHECK_LOGIN, "1");

							Intent intent = new Intent(mContext,
									InstallCheckerService.class);
							intent.putExtra("namePackage", appPackageName);
							startService(intent);
						} else {
							Log.d("Luong",
									"========================== Kill App");
							 doRestart(mContext);
						}
					}
				} catch (Exception e) {
					Toast.makeText(mContext, "Error when connect to server",
							Toast.LENGTH_LONG).show();
				}
			}
		}
	};

}
